package com.qidian.zl.paper.servlets;

import com.qidian.zl.paper.factory.ServiceFactory;
import com.qidian.zl.paper.pojo.Admin;
import com.qidian.zl.paper.service.AdminService;
import com.qidian.zl.paper.util.DateUtils;
import com.qidian.zl.paper.util.JsonTools;
import com.qidian.zl.paper.util.SessionUtil;
import com.qidian.zl.paper.util.StResult;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.Map;

@WebServlet(urlPatterns = {"/admin/logincheck", "/admin/login", "/admin/queryById", "/admin/edit", "/admin/query", "/admin/save"})
public class AdminServlet extends HttpServlet {
    private AdminService adminService = ServiceFactory.getAdminService();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
        if (uri.endsWith("/admin/query")) {
            query(request, response);
        } else if (uri.endsWith("admin/save")) {
            save(request, response);
        } else if (uri.endsWith("admin/edit")) {
            edit(request, response);
        } else if (uri.endsWith("queryById")) {
            queryById(request, response);
        } else if (uri.endsWith("login")) {
            login(request, response);
        } else if (uri.endsWith("logincheck")) {
            checklogin(request, response);
        }
    }

    private void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        Admin admin = adminService.login(request.getParameter("adminName"),request.getParameter("adminPass"));
        if(admin==null){
            result = StResult.fail("用户名或密码错误");
        }else{
            admin.setAdminPass(null);//清空密码
            //将admin放入session
            request.getSession().setAttribute("loginInfo",admin);
            result = StResult.ok("登陆成功");
            Cookie cookie = new Cookie("JSESSIONID",request.getSession().getId());
            response.addCookie(cookie);
            Cookie cookie1 = new Cookie("token",request.getSession().getId());
            cookie1.setPath("/paper");
            response.addCookie(cookie1);
        }
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));

    }

    private void checklogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        String sessionId = request.getParameter("sessionId");
        if(sessionId==null || "".equals("sessionId") || "undefined".equals(sessionId)){
            result = StResult.fail();
        }else {
            Map<String, Object> session = SessionUtil.getSession(sessionId);
            Object obj = session.get("loginInfo");
            if (obj != null) {
                result = StResult.ok(obj);
            } else {
                result = StResult.fail();
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(request));
    }

    private void queryById(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = StResult.ok(adminService.queryById(Long.parseLong(request.getParameter("adminId"))));
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result=null;
        Admin admin=new Admin();
        try{
            admin.setAdminId(Long.parseLong(request.getParameter("adminId")));
            admin.setAdminPass(request.getParameter("adminPass"));
            admin.setAdminName(request.getParameter("adminName"));
            admin.setAdminStatus(Integer.parseInt(request.getParameter("adminStatus")));
            admin.setAdminCreated(DateUtils.getNow());
            int r=adminService.update(admin);
            if(r==1){
                result=StResult.ok("修改成功");
            }else if(r==2){
                result=new StResult(405,"登录名重复");

            }else {
                result=StResult.fail("修改失败");
            }

        }catch (Exception e){
            e.printStackTrace();
            result=StResult.fail("添加失败");
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(request));
    }

    private void save(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        Admin admin = new Admin();
        try {
            admin.setAdminPass(request.getParameter("adminPass"));
            admin.setAdminName(request.getParameter("adminName"));
            admin.setAdminCreated(DateUtils.getNow());
            admin.setAdminStatus(Integer.parseInt(request.getParameter("adminStatus")));
            int r = adminService.save(admin);
            if (r == 1) {
                result = StResult.ok("添加成功");
            } else if (r == 2) {
                result = new StResult(405, "登陆名重复");
            } else {
                result = StResult.fail("添加失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = StResult.fail("添加失败");
        }// 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }


    private void query(HttpServletRequest request, HttpServletResponse response) throws IOException {
        StResult result = null;
        int page =1;
        int size = 10;
        try{page = Integer.parseInt(request.getParameter("page"));}catch (Exception e){}
        try{size = Integer.parseInt(request.getParameter("size"));}catch (Exception e){}
        Admin admin = new Admin();
        try {
            admin.setAdminName(request.getParameter("adminName"));
            admin.setAdminStatus(Integer.parseInt(request.getParameter("adminStatus")));
        }catch (Exception e){}
        result = adminService.queryByPage(page, size, admin);
        // 输出result对象
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JsonTools.obj2String(result));
    }


}
